package com.lixiaoyi.config.security.service;

import com.lixiaoyi.entity.Permission;
import com.lixiaoyi.entity.User;
import com.lixiaoyi.service.PermissionService;
import com.lixiaoyi.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 李小毅
 * @Description
 * @Date 2022-07-01
 */

// 用户认证处理类
@Component
public class CustomerUserDetailsService implements UserDetailsService {

    @Resource
    private UserService userService;

    @Resource
    private PermissionService permissionService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 调用根据用户名查询用户信息的方法
        User user = userService.findUserByUserName(username);
        // 判断对象是否为空 如果为空 表示登陆失败
        if (user==null){
            throw new UsernameNotFoundException("用户名或密码错误！");
        }
        // 查询当前登录用户拥有的权限列表
        List<Permission> permissionList = permissionService.findPermissionListByUserId(user.getId());
        // 获取对应的权限编码
        List<String> codeList = permissionList.stream()
                .filter(item -> item != null)
                .map(item -> item.getCode())
                .filter(item -> item != null)
                .collect(Collectors.toList());
        // 将权限编码列表 转皇城数据
        String[] strings = codeList.toArray(new String[codeList.size()]);
        // 设置权限列表
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(strings);
        // 将权限列表设置给user对象
        user.setAuthorities(authorityList);
        // 设置用户拥有的菜单信息
        user.setPermissionList(permissionList);

        // 查询成功
        return user;

    }
}
